#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Anki卡片生成工具
支持将TXT文件转换为Anki可导入的问答卡片
"""

import re
import os
import sys
from typing import List, Dict, Tuple
import argparse
from pathlib import Path

class AnkiCard:
    """Anki卡片数据结构"""
    def __init__(self):
        self.question = ""
        self.category = ""
        self.core_answer = ""
        self.full_explanation = ""
        self.memory_tip = ""
        self.common_mistake = ""
        self.essential_understanding = ""

class AnkiCardGenerator:
    """Anki卡片生成器主类"""
    
    def __init__(self):
        self.cards: List[AnkiCard] = []
        
    def parse_txt_file(self, file_path: str) -> List[Dict]:
        """
        解析TXT文件内容
        支持两种格式：
        1. 自定义格式（使用指定分隔符）
        2. 简易格式（问题\t答案）
        """
        try:
            # 尝试多种编码读取
            content = None
            for encoding in ['utf-8', 'utf-8-sig', 'gb2312', 'gbk', 'gb18030']:
                try:
                    with open(file_path, 'r', encoding=encoding) as f:
                        content = f.read().strip()
                    print(f"使用编码: {encoding}")
                    break
                except UnicodeDecodeError:
                    continue
            
            if content is None:
                print("无法识别文件编码，请确保文件为UTF-8或GBK编码")
                return []
            
            # 尝试解析自定义格式
            if "===============" in content and "---" in content:
                return self._parse_custom_format(content)
            else:
                # 尝试解析简易格式
                return self._parse_simple_format(content)
                
        except Exception as e:
            print(f"文件读取错误: {e}")
            return []
    
    def _parse_custom_format(self, content: str) -> List[Dict]:
        """解析自定义格式"""
        cards = []
        card_blocks = content.split("===============")
        
        for block in card_blocks:
            block = block.strip()
            if not block:
                continue
                
            # 分割正面和背面
            if "---" not in block:
                continue
                
            front, back = block.split("---", 1)
            front_lines = [line.strip() for line in front.strip().split('\n') if line.strip()]
            back_lines = [line.strip() for line in back.strip().split('\n') if line.strip()]
            
            if len(front_lines) < 1:  # 至少要有问题
                continue
                
            card = {
                'question': front_lines[0],
                'category': front_lines[1] if len(front_lines) > 1 else '未分类',
                'core_answer': '',
                'full_explanation': '',
                'memory_tip': '',
                'common_mistake': '',
                'essential_understanding': ''
            }
            
            # 解析背面内容 - 支持多行文本
            current_field = None
            current_content = []
            
            for line in back_lines:
                if line.startswith('✅'):
                    # 如果之前有累积的内容，先保存
                    if current_field and current_content:
                        card[current_field] = '\n'.join(current_content).strip()
                    # 开始新的字段
                    current_field = 'core_answer'
                    current_content = [line[1:].strip()]
                elif line.startswith('📚'):
                    if current_field and current_content:
                        card[current_field] = '\n'.join(current_content).strip()
                    current_field = 'full_explanation'
                    current_content = [line[1:].strip()]
                elif line.startswith('❗'):
                    if current_field and current_content:
                        card[current_field] = '\n'.join(current_content).strip()
                    current_field = 'memory_tip'
                    current_content = [line[1:].strip()]
                elif line.startswith('⛔️'):
                    if current_field and current_content:
                        card[current_field] = '\n'.join(current_content).strip()
                    current_field = 'common_mistake'
                    current_content = [line[1:].strip()]
                elif line.startswith('🔍'):
                    if current_field and current_content:
                        card[current_field] = '\n'.join(current_content).strip()
                    current_field = 'essential_understanding'
                    current_content = [line[1:].strip()]
                else:
                    # 如果是续行，添加到当前字段
                    if current_field and current_content:
                        current_content.append(line)
                    elif line.strip():  # 如果是第一行且没有标记
                        current_content.append(line)
            
            # 保存最后一个字段的内容
            if current_field and current_content:
                card[current_field] = '\n'.join(current_content).strip()
            
            cards.append(card)
        
        return cards
    
    def _parse_simple_format(self, content: str) -> List[Dict]:
        """解析简易格式（问题\t答案）"""
        cards = []
        lines = [line.strip() for line in content.split('\n') if line.strip()]
        
        for line in lines:
            if '\t' in line:
                question, answer = line.split('\t', 1)
                card = {
                    'question': question.strip(),
                    'category': '未分类',
                    'core_answer': answer.strip(),
                    'full_explanation': '',
                    'memory_tip': '',
                    'common_mistake': '',
                    'essential_understanding': ''
                }
                cards.append(card)
        
        return cards
    
    def create_template_card(self, question: str, category: str, core_answer: str, 
                           full_explanation: str = "", memory_tip: str = "", 
                           common_mistake: str = "", essential_understanding: str = "") -> AnkiCard:
        """创建模板卡片"""
        card = AnkiCard()
        card.question = question
        card.category = category
        card.core_answer = core_answer
        card.full_explanation = full_explanation
        card.memory_tip = memory_tip
        card.common_mistake = common_mistake
        card.essential_understanding = essential_understanding
        return card
    
    def format_for_anki(self, cards: List[AnkiCard]) -> str:
        """格式化为Anki可导入的制表符分隔格式"""
        lines = []
        
        # 添加标题行
        lines.append("问题\t知识点分类\t核心答案\t完整解析\t记忆技巧\t我的误区\t本质理解")
        
        for card in cards:
            # 转义制表符，保留换行符用<br>标签以便在Anki中正确显示多行文本
            question = str(card.question).replace('\t', ' ').replace('\n', '<br>')
            category = str(card.category).replace('\t', ' ').replace('\n', '<br>')
            core_answer = str(card.core_answer).replace('\t', ' ').replace('\n', '<br>')
            full_explanation = str(card.full_explanation).replace('\t', ' ').replace('\n', '<br>')
            memory_tip = str(card.memory_tip).replace('\t', ' ').replace('\n', '<br>')
            common_mistake = str(card.common_mistake).replace('\t', ' ').replace('\n', '<br>')
            essential_understanding = str(card.essential_understanding).replace('\t', ' ').replace('\n', '<br>')
            
            line = f"{question}\t{category}\t{core_answer}\t{full_explanation}\t{memory_tip}\t{common_mistake}\t{essential_understanding}"
            lines.append(line)
        
        return '\n'.join(lines)
    
    def export_to_file(self, content: str, output_path: str):
        """导出到文件"""
        try:
            # 使用UTF-8 with BOM确保兼容性
            with open(output_path, 'w', encoding='utf-8-sig') as f:
                f.write(content)
            print(f"成功导出到: {output_path}")
            print("文件已使用UTF-8编码保存，支持emoji和特殊字符")
        except Exception as e:
            print(f"导出失败: {e}")
    
    def generate_sample_template(self) -> str:
        """生成示例模板文件"""
        sample = """光纤通道(FC)为何更适合金融高频交易场景？
存储协议
---
✅ 微秒级延迟要求+零丢包保障
📚 光纤协议栈比TCP/IP精简，省略了重传和拥塞控制机制，直接映射到物理层
❗ FC像F1赛车（专用赛道/极简设计），IP像货车（通用公路/频繁检修）
⛔️ 曾将网络带宽视为低延迟首要因素，忽略了协议开销的影响
🔍 延迟敏感型系统需要绕过传统协议栈的冗余机制
===============
IP SAN和FC SAN的主要区别是什么？
存储协议
---
✅ 传输协议不同：FC使用光纤通道协议，IP SAN使用TCP/IP协议
📚 FC SAN专为存储设计，提供predictable性能；IP SAN基于现有IP网络，成本更低但性能有波动
❗ FC像专用高速公路，IP SAN像普通公路共享车流
⛔️ 曾认为两者只是速度差异，忽略了协议可靠性的根本区别
🔍 选择取决于对性能可预测性和成本的不同权衡
==============="""
        return sample

def main():
    """主函数"""
    parser = argparse.ArgumentParser(description='Anki卡片生成工具')
    parser.add_argument('--input', '-i', help='输入TXT文件路径')
    parser.add_argument('--output', '-o', help='输出文件路径')
    parser.add_argument('--sample', action='store_true', help='生成示例模板文件')
    
    args = parser.parse_args()
    
    generator = AnkiCardGenerator()
    
    if args.sample:
        # 生成示例模板
        sample_content = generator.generate_sample_template()
        sample_path = "sample_template.txt"
        generator.export_to_file(sample_content, sample_path)
        print(f"示例模板已生成: {sample_path}")
        return
    
    if not args.input:
        print("请提供输入文件路径，或使用 --sample 生成示例模板")
        return
    
    # 解析输入文件
    parsed_cards = generator.parse_txt_file(args.input)
    
    if not parsed_cards:
        print("未能解析任何卡片，请检查文件格式")
        return
    
    # 转换为Anki卡片对象
    anki_cards = []
    for card_data in parsed_cards:
        card = generator.create_template_card(
            question=card_data['question'],
            category=card_data['category'],
            core_answer=card_data['core_answer'],
            full_explanation=card_data['full_explanation'],
            memory_tip=card_data['memory_tip'],
            common_mistake=card_data['common_mistake'],
            essential_understanding=card_data['essential_understanding']
        )
        anki_cards.append(card)
    
    # 格式化输出
    anki_content = generator.format_for_anki(anki_cards)
    
    # 确定输出路径
    output_path = args.output or "anki_cards_export.txt"
    
    # 导出
    generator.export_to_file(anki_content, output_path)
    
    print(f"成功处理了 {len(anki_cards)} 张卡片")
    print("导入Anki步骤:")
    print("1. 打开Anki")
    print("2. 选择要导入的牌组")
    print("3. 点击 文件 -> 导入")
    print("4. 选择导出的文件")
    print("5. 字段分隔符选择 '制表符'")
    print("6. 确认字段映射正确")
    print("7. 点击导入")

if __name__ == "__main__":
    main()